<template>
  <div class="app-container">
    <el-row :gutter="8">
      <el-col :span="8">
        <el-card class="card-h-100">
          <div class="pb-10">
            <el-input v-model="filterText" size="mini" placeholder="输入关键字进行过滤" />
          </div>
          <div class="tree-warp">
            <el-tree
              ref="tree"
              class="filter-tree"
              node-key="id"
              :data="data"
              :props="defaultProps"
              default-expand-all
              :filter-node-method="filterNode"
              :highlight-current="isShowGaoliang"
              @node-click="handleNodeClick"
            />
          </div>
        </el-card>
      </el-col>
      <el-col :span="16">
        <el-card class="card-h-100">
          <div class="text-right">
            <el-button type="primary" :style="{ display: visibleCreateBtn }" size="mini" icon="el-icon-plus" @click="add">新建</el-button>
            <el-button size="mini" :style="{ display: visibleUpdateBtn }" icon="el-icon-check" @click="update">保存</el-button>
            <el-button size="mini" :style="{ display: visibleUpdateBtn }" icon="el-icon-delete" @click="delNode">删除</el-button>
          </div>
          <el-divider />
          <el-form ref="myform" :model="formItem" :rules="rules" label-width="100px" size="mini">
            <el-form-item label="分类名称" prop="name" :style="{ display: (formItem.code === -1 || formItem.code === '') ? 'none':'' }">
              <el-input v-model="formItem.name" placeholder="请输入分类名称" :disabled="visibleUpdateBtn==='none'" />
            </el-form-item>
            <el-form-item label="分类编码" prop="code" :style="{ display: (formItem.code === -1 || formItem.code === '') ? 'none':'' }">
              <el-input v-model="formItem.code" placeholder="请输入分类编码" :disabled="visibleUpdateBtn==='none'" />
            </el-form-item>
            <el-form-item label="计量单位" prop="measureUnit" :style="{ display: (formItem.code === -1 || formItem.code === '') ? 'none':'' }">
              <el-input v-model="formItem.measureUnit" :placeholder="visibleUpdateBtn==='none' ? '':'请输入计量单位'" :disabled="visibleUpdateBtn==='none'" />
            </el-form-item>
            <el-form-item label="分类顺序" prop="sort" :style="{ display: (formItem.code === -1 || formItem.code === '') ? 'none':'' }">
              <el-input v-model="formItem.sort" placeholder="请输入分类顺序" :disabled="visibleUpdateBtn==='none'" />
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
    <FormDialog title="新建" :show="dialogFormVisible" width="40%" @on-ok="ok" @on-cancel="cancel">
      <EditForm ref="editForm" :parent-id="parentId" :parent-name="parentName" />
    </FormDialog>
  </div>
</template>
<script>
import FormDialog from '@neu/biz-core/components/FormDialog'
import EditForm from './components/editForm'
import { tree } from '@neu/dcam-ui/api/assetType'
import {
  update,
  remove
} from '@neu/dcam-ui/api/assetType'

// 定义一个表单原始项
const formItem = {
  id: '',
  name: '',
  code: '',
  measureUnit: '',
  sort: '',
  parentId: null
}

export default {
  name: 'AssetTypeTreePage',
  components: {
    FormDialog,
    EditForm
  },

  mixins: [],
  data() {
    return {
      filterText: '',
      isShowGaoliang: false,
      visibleCreateBtn: 'none',
      visibleUpdateBtn: '',
      /** 资产分类树 */
      data: [],
      d: remove,
      defaultProps: {
        id: 'code',
        label: 'title',
        children: 'children'
      },
      formItem: {
        ...formItem
      },
      // 表单验证规则
      rules: {
        name: [{
          required: true,
          message: '分类名称不能为空',
          trigger: 'blur'
        },
        {
          validator: function(rule, value, callback) {
            if (value.length > 50) {
              callback(new Error('最多可输入50个字符'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }],
        code: [{
          required: true,
          message: '分类编码不能为空',
          trigger: 'blur'
        },
        {
          validator: function(rule, value, callback) {
            if (value.length > 50) {
              callback(new Error('最多可输入50个字符'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }],
        measureUnit: [{
          required: false,
          message: '计量单位不能为空',
          trigger: 'blur'
        },
        {
          validator: function(rule, value, callback) {
            if (value && value.length > 10) {
              callback(new Error('最多可输入10个字符'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
        ],
        sort: [{
          required: true,
          message: '分类不能为空',
          trigger: 'blur'
        },
        {
          validator: function(rule, value, callback) {
            if (/^[0-9]*$/.test(value) === false) {
              callback(new Error('请输入正确的数字'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
        ]
      },
      dialogFormVisible: false,
      parentId: null,
      parentName: ''
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.tree()
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true
      return data.title.indexOf(value) !== -1
    },
    // 分类树
    tree() {
      tree().then(response => {
        const treeData = [{ code: -1, title: '资产分类', children: response.data, attr: { id: -1, parentId: -1, sort: 0 }}]
        this.data = treeData

        this.$refs.tree.$emit('node-click', this.$refs.tree)
      })
    },
    // 点击节点名称触发的事件
    handleNodeClick: function(data, node) {
      if ((node && node.level < 2) || !node) {
        this.visibleCreateBtn = 'none'
      } else {
        this.visibleCreateBtn = ''
      }

      if ((node && node.level < 3) || !node) {
        this.visibleUpdateBtn = 'none'
      } else {
        this.visibleUpdateBtn = ''
      }

      if (typeof data.code !== 'undefined') {
        this.formItem.code = data.code
        this.formItem.name = data.title
        this.formItem.measureUnit = data.attr.measureUnit
        this.formItem.sort = data.attr.sort
        this.formItem.id = data.attr.id
        this.formItem.parentId = data.attr.parentId
        this.lightNode(this.formItem.code)
      } else {
        if (this.formItem.code !== '') {
          this.lightNode(this.formItem.code)
        }
      }
    },
    // 高亮显示节点
    lightNode: function(id) {
      this.$nextTick(() => {
        // 使树筛选时选中的节点高亮显示
        this.isShowGaoliang = true
        this.$refs.tree.setCurrentKey(id)
      })
    },
    update() {
      const that = this
      if (!this.operationValidate()) return
      this.edit().then(response => {
        if (response === false) return
        this.$message({
          showClose: true,
          message: '操作成功！',
          type: 'success'
        })
        that.tree()
      })
    },
    edit() {
      if (!this.operationValidate()) return
      return new Promise(resolve => {
        this.$refs.myform.validate((valid) => {
          if (valid) {
            resolve(update(this.formItem.id, this.formItem))
          } else {
            resolve(false)
          }
        })
      })
    },
    operationValidate() {
      if (this.formItem.code === '') {
        this.$message({
          showClose: true,
          message: '请选择一个树节点！',
          type: 'error'
        })
        return false
      }
      return true
    },
    delNode() {
      if (!this.operationValidate()) return
      this.remove().then(response => {
        if (response === false) return
        this.$message({
          showClose: true,
          message: '操作成功！',
          type: 'success'
        })
        this.tree()
        this.formItem.id = -1
        this.$refs.myform.resetFields()
      })
    },
    // 删除
    remove() {
      return new Promise(resolve => {
        this.$refs.myform.validate((valid) => {
          if (valid) {
            resolve(remove(this.formItem.id))
          } else {
            resolve(false)
          }
        })
      })
    },
    // 新建
    add() {
      if (!this.operationValidate()) return
      this.parentId = this.formItem.id
      this.parentName = this.formItem.name
      this.dialogFormVisible = true
    },
    ok() {
      // 直接调用表单实例的保存方法
      this.$refs.editForm.save().then(response => {
        if (response === false) return
        this.$message({
          showClose: true,
          message: '操作成功！',
          type: 'success'
        })

        this.tree()
        // 关闭对话框
        this.dialogFormVisible = false
        this.$refs.editForm.reset()
      })
    },
    cancel() {
      this.$refs.editForm.reset()
      this.dialogFormVisible = false
    }
  }
}
</script>
<style type="scss" scoped>
.tree-warp{
  overflow: auto;
  height:calc(100vh - 150px)
}
</style>
